<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //
      class Eventbus {
        constructor() {
          //定义个一个map类储存时间
          (this.eventMap = this.eventMap || new Map()),
            //设定一个绑定事件上限
            (this.maxEvent = this.maxEvent || 10);
        }
      }

      //构建原型触发事件原型方法$emit type事件名称  arg传递的数据
      Eventbus.prototype.emit = function (type, ...arg) {
        //获取map里储存的事件回调
        let handel = this.eventMap.get(type);
        console.log(handel);
        //判读是否存储多个回调
        if (Array.isArray(handel)) {
          //多个回调, 循环依次触发
          handel.forEach((item) => {
            //判断参数是否是多个
            if (arg.length > 1) {
              item.apply(this, arg);
            } else {
              item.call(this, ...arg);
            }
          });
        } else if (typeof handel === "function") {
          if (arg.length > 1) {
            handel.apply(this, arg);
          } else {
            handel.call(this);
          }
        } else {
          return new Error(`not find ${type}`);
        }
      };

      //构建负责绑定,监听事件的$on
      Eventbus.prototype.on = function (type, callback) {
        let handel = this.eventMap.get(type);

        if (!handel) {
          //没有绑定时间
          this.eventMap.set(type, callback);
        } else if (handel && typeof handel === "function") {
          //判断在这个回调存储之前是否还有其他的回调存储

          //表明之前有且只有一个回调,则以数组形式储存
          this.eventMap.set(type, [handel, callback]);
        } else {
          //判断是否是符合规定回调数量
          if (handel.length === this.maxEvent) {
            throw new Error(`太多啦`);
          }
          //如果是数组形式则表示存在多个回调
          handel.push(callback);
        }
      };

      const eventbus = new Eventbus();
      let name = "渣渣辉";

      eventbus.on("niubi", () => {
        console.log("我是马牛逼");
      });
      eventbus.on("niubi", (name) => {
        console.log(name);
      });
      eventbus.emit("niubi", name);
      // eventbus.emit("niubi", name);
    </script>
  </body>
</html>
